#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <functional>
#include <cstring>
#include <cstdlib>
#include "Protocol.hpp"
#include <wait.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <string>
namespace server
{
    using namespace std;

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR,
        ACCEPT_ERR,
        OPEN_ERR
    };
    static const int gbacklog = 5;
    static const uint16_t gport = 8080;
    using func_t = function<bool(const HttpRequest &, HttpResponse &)>;

    class HttpServer
    {
    public:
        HttpServer(func_t func, const uint16_t &port = gport)
            : _listensock(-1), _port(port), _func(func)
        {
        }

        void initServer()
        {
            // 1.创建socket套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                exit(SOCKET_ERR);
            }

            // 2.bind绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_family = AF_INET;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof local) < 0)
            {
                exit(BIND_ERR);
            }

            // 3.设置socket 为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                exit(LISTEN_ERR);
            }
        }
        void HandlerHttp(int sock)
        {
            // 1. 读到完整的http请求
            // 2. 反序列化
            // 3. httprequst, httpresponse, _func(req, resp)
            // 4. resp序列化
            // 5. send
            char buffer[4096];
            HttpRequest req;
            HttpResponse resp;
            size_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                req.inbuffer = buffer;
                req.parse();
                _func(req, resp);
                send(sock, resp.outbuffer.c_str(), resp.outbuffer.size(), 0);
            }
        }
        void start()
        {

            for (;;)
            {
                // 4.server获取新链接
                // sock和client进行通信的fd
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    exit(ACCEPT_ERR);
                }

                // 5.这里就是一个sock,未来通信我们就用这个sock,面向字节流，后续全部都是文件的操作。
                // 多进程版本(2)
                pid_t id = fork();
                if (id == 0)
                {
                    close(_listensock);
                    if(fork()>0)exit(0);
                    HandlerHttp(sock);
                    close(sock); // 对于一个使用完毕的sock,我们要关闭这个sock,否则会导致文件描述符泄露
                    exit(0);
                }
                close(sock);


            }
        }
        ~HttpServer() {}

    private:
        int _listensock;
        uint16_t _port;
        func_t _func;
    };

}